<template>
  <div class="console">
    <!--数据卡片-->
    <n-grid cols="1 s:2 m:3 l:4 xl:4 2xl:4" responsive="screen" :x-gap="12" :y-gap="8">
      <n-grid-item>
        <NCard
          title="文章总数"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="success">统计</n-tag>
          </template>
          <div class="flex justify-between px-1 py-1">
            <n-skeleton v-if="loading" :width="100" size="medium" />
            <span v-else class="text-3xl">{{ articleCount }}</span>
          </div>

        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard
          title="交易总量"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="info">统计</n-tag>
          </template>
          <div class="flex justify-between px-1 py-1">
            <n-skeleton v-if="loading" :width="100" size="medium" />
            <span v-else class="text-3xl">{{ secondItemCountInfo.orderCount || 0 }}</span>
          </div>
          <template #footer>
            <div class="flex justify-between">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                <div class="text-sn"> 总交易额： </div>
                <div class="text-sn">
                  <span>¥{{ secondItemCountInfo.totalAmount || 0 }}</span>
                </div>
              </template>
            </div>
          </template>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard
          title="灾害总数"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="warning">统计</n-tag>
          </template>
          <div class="flex justify-between px-1 py-1">
            <n-skeleton v-if="loading" :width="100" size="medium" />
            <span v-else class="text-3xl">{{ disasterCount }}</span>
          </div>
          <div class="grid grid-cols-2 gap-2 px-1 py-1">
            <div class="text-sn" v-for="(chineseName, index) in disasterTypeNames" :key="index">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                {{ chineseName }}：
                <span>{{ getDisasterTypeCount(chineseName) }}</span>
              </template>
            </div>
          </div>
          <template #footer>
            <div class="flex justify-between">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                <div class="text-sn"> 已处理： </div>
                <div class="text-sn">
                  <span>{{ Math.floor(disasterCount * 0.6) }}</span>
                </div>
              </template>
            </div>
          </template>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard
          title="用户总数"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="error">统计</n-tag>
          </template>
          <div class="flex justify-between px-1 py-1">
            <n-skeleton v-if="loading" :width="100" size="medium" />
            <span v-else class="text-3xl">{{ userCount }}</span>
          </div>
          <template #footer>
            <div class="flex justify-between">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                <div class="text-sn"> 新增用户： </div>
                <div class="text-sn">
                  <span>{{ getTodayNewUsers() }}</span>
                </div>
              </template>
            </div>
          </template>
        </NCard>
      </n-grid-item>
    </n-grid>

    <!--导航卡片-->
    <div class="mt-4">
      <n-grid cols="1 s:2 m:3 l:4 xl:4 2xl:4" responsive="screen" :x-gap="16" :y-gap="8">
        <!-- 灾害验证 -->
        <n-grid-item>
          <NCard content-style="padding-top: 0;" size="small" :bordered="false">
            <template #footer>
              <n-skeleton v-if="loading" size="medium" />
              <div class="cursor-pointer" v-else @click="router.push('/disaster/list')">
                <p class="flex justify-center">
                  <span>
                    <n-icon :size="32" class="flex-1" color="#ff9c6e">
                      <ThunderboltOutlined />
                    </n-icon>
                  </span>
                </p>
                <p class="flex justify-center">
                  <span>灾害验证</span>
                </p>
              </div>
            </template>
          </NCard>
        </n-grid-item>
        
        <!-- 举报处理 -->
        <n-grid-item>
          <NCard content-style="padding-top: 0;" size="small" :bordered="false">
            <template #footer>
              <n-skeleton v-if="loading" size="medium" />
              <div class="cursor-pointer" v-else @click="router.push('/report/list')">
                <p class="flex justify-center">
                  <span>
                    <n-icon :size="32" class="flex-1" color="#ffd666">
                      <WarningOutlined />
                    </n-icon>
                  </span>
                </p>
                <p class="flex justify-center">
                  <span>举报处理</span>
                </p>
              </div>
            </template>
          </NCard>
        </n-grid-item>
        
        <!-- 文章审核 -->
        <n-grid-item>
          <NCard content-style="padding-top: 0;" size="small" :bordered="false">
            <template #footer>
              <n-skeleton v-if="loading" size="medium" />
              <div class="cursor-pointer" v-else @click="router.push('/addedList/index')">
                <p class="flex justify-center">
                  <span>
                    <n-icon :size="32" class="flex-1" color="#69c0ff">
                      <FileTextOutlined />
                    </n-icon>
                  </span>
                </p>
                <p class="flex justify-center">
                  <span>文章审核</span>
                </p>
              </div>
            </template>
          </NCard>
        </n-grid-item>
        
        <!-- 用户管理 -->
        <n-grid-item>
          <NCard content-style="padding-top: 0;" size="small" :bordered="false">
            <template #footer>
              <n-skeleton v-if="loading" size="medium" />
              <div class="cursor-pointer" v-else @click="router.push('/userList/index')">
                <p class="flex justify-center">
                  <span>
                    <n-icon :size="32" class="flex-1" color="#b37feb">
                      <UserOutlined />
                    </n-icon>
                  </span>
                </p>
                <p class="flex justify-center">
                  <span>用户管理</span>
                </p>
              </div>
            </template>
          </NCard>
        </n-grid-item>
      </n-grid>
    </div>
    
    <!--添加数据图表组件-->
    <div class="mt-4">
      <DataCharts 
        :disasterTypeData="disasterTypeData" 
        :disasterMapData="disasterMapData"
        :articleData="{
          months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          values: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330]
        }"
        :userActivityData="userActivityData"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getConsoleInfo } from '@/api/dashboard/console';
import DataCharts from './DataCharts.vue'; // 导入图表组件
import { AdminManagementApi } from "@/api/new/AdminManagementApi";
import { RoadDisasterApi } from "@/api/RoadDisasterApi";
import {
  CaretUpOutlined,
  CaretDownOutlined,
  ThunderboltOutlined,
  WarningOutlined,
  FileTextOutlined,
  UserOutlined
} from '@vicons/antd';

// 使用路由
const router = useRouter();

// 灾害类型映射表 - 添加英文到中文的映射
const hazardTypeMap = {
  'landslid': '山体滑坡',
  'roadflooding': '内涝',
  'waterbody': '水体',
  'road_collapse': '路面塌陷',
  'road_frozing': '路面结冰'
};

// 提取中文名称数组，用于v-for循环
const disasterTypeNames = Object.values(hazardTypeMap);

const loading = ref(true);
const visits = ref(0);
const saleroom = ref(0);
const orderLarge = ref(0);
const volume = ref(0);

const articleCount = ref(0);
const secondItemCountInfo = ref({});
const disasterCount = ref(0);
const userCount = ref(0);
const disasterTypeData = ref([]);
const disasterMapData = ref([]);
const userActivityData = ref({
  days: [],
  values: []
});

// 获取特定类型的灾害数量
const getDisasterTypeCount = (typeName) => {
  if (!disasterTypeData.value || !Array.isArray(disasterTypeData.value) || disasterTypeData.value.length === 0) return 0;
  
  const typeItem = disasterTypeData.value.find(item => item.name === typeName);
  return typeItem ? typeItem.value : 0;
};

// 获取今日新增用户数
const getTodayNewUsers = () => {
  if (!userActivityData.value || !userActivityData.value.days || userActivityData.value.days.length === 0) return 0;
  
  // 获取最后一天（今天）的数据
  const todayIndex = userActivityData.value.days.length - 1;
  return userActivityData.value.values[todayIndex] || 0;
};

const fetchAdminData = async () => {
  try {
    // 1.文章数据
    const res1 = await AdminManagementApi.getTotalArticleCount();
    articleCount.value = JSON.parse(res1).articleCount;//文章总数

    // 2.获取交易总量
    const secondItemRes = await AdminManagementApi.getTotalTransaction();
    secondItemCountInfo.value = JSON.parse(secondItemRes); //{"orderCount":0,"totalAmount":0.00}

    // 3.获取灾害总信息
    const disasterRes = await RoadDisasterApi.getAllRoadDisasters();
    console.log('灾害数据原始数组:', disasterRes);
    disasterCount.value = disasterRes.length || 0;
    
    // 处理灾害数据，按类型分类统计
    const disasterTypeStats = {
      'roadflooding': 0,  // 内涝
      'landslid': 0,      // 山体滑坡
      'road_collapse': 0, // 路面塌陷
      'waterbody': 0,     // 水体
      'road_frozing': 0,  // 路面结冰
      'other': 0          // 其他类型
    };
    
    // 处理灾害地理位置数据，用于地图展示
    const disasterGeoData = [];
    
    // 打印每个灾害的类型，确保数据正确
    if (Array.isArray(disasterRes)) {
      disasterRes.forEach((disaster, index) => {
        console.log(`灾害 ${index}:`, disaster.disasterType, hazardTypeMap[disaster.disasterType] || '未知类型');
        
        // 统计灾害类型
        if (disasterTypeStats.hasOwnProperty(disaster.disasterType)) {
          disasterTypeStats[disaster.disasterType]++;
        } else {
          disasterTypeStats.other++;
        }
        
        // 收集地理位置数据
        if (disaster.longitude && disaster.latitude) {
          disasterGeoData.push({
            name: `灾害ID:${disaster.disasterID}`,
            value: [disaster.longitude, disaster.latitude, 1],
            disasterType: disaster.disasterType,
            info: disaster.disasterInfo
          });
        }
      });
    }
    
    console.log('灾害类型统计:', disasterTypeStats);
    
    // 将处理后的数据存储，供图表使用
    disasterTypeData.value = [];
    
    // 添加所有灾害类型，即使数量为0
    Object.keys(hazardTypeMap).forEach(key => {
      disasterTypeData.value.push({
        value: disasterTypeStats[key] || 0,
        name: hazardTypeMap[key]
      });
    });
    
    console.log('处理后的灾害类型数据:', disasterTypeData.value);
    
    disasterMapData.value = disasterGeoData;

    // 4.获取用户总量
    const userRes = await AdminManagementApi.getUserList(1,10000);
    const userParsedRes = JSON.parse(userRes);
    console.log('用户', userParsedRes.data);
    
    // 处理用户数据
    const userData = userParsedRes.data || [];
    userCount.value = userData.length;
    
    // 按创建时间统计用户增长趋势
    const userGrowthData = {};
    const today = new Date();
    const last7Days = [];
    
    // 生成最近7天的日期
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      const dateStr = `${date.getMonth() + 1}/${date.getDate()}`;
      last7Days.push(dateStr);
      userGrowthData[dateStr] = 0;
    }
    
    // 统计每天的新用户数量
    userData.forEach(user => {
      if (user.createTime) {
        const createDate = new Date(user.createTime);
        const createDateStr = `${createDate.getMonth() + 1}/${createDate.getDate()}`;
        
        // 如果是最近7天内的用户
        if (userGrowthData.hasOwnProperty(createDateStr)) {
          userGrowthData[createDateStr]++;
        }
      }
    });
    
    // 转换为图表所需的格式
    userActivityData.value = {
      days: last7Days,
      values: last7Days.map(day => userGrowthData[day] || 0)
    };
    
    loading.value = false;
  } catch (error) {
    console.error('获取管理员数据失败:', error);
    loading.value = false;
  }
};

onMounted(async () => {
  const data = await getConsoleInfo();
  visits.value = data.visits;
  saleroom.value = data.saleroom;
  orderLarge.value = data.orderLarge;
  volume.value = data.volume;
  loading.value = false;

  // 获取admin数据
  fetchAdminData();
});
</script>

<style lang="less" scoped>
.console {
  .n-card {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .n-card-__content {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
  }

  .n-card-__content > div:nth-child(2) {
    flex-grow: 1;
    min-height: 80px;
  }

  .text-3xl {
    font-size: 1.875rem;
    line-height: 2.25rem;
    font-weight: bold;
  }
}
</style>
